package com.wenx.v3openfeign.api.fallback;

import com.wenx.v3core.response.R;
import com.wenx.v3openfeign.api.SysUserRemoteInfra;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

/**
 * 系统用户远程服务熔断降级工厂
 * 当远程服务调用失败时，提供降级处理逻辑
 * 确保认证服务的稳定性和可用性
 */
@Slf4j
@Component
public class SysUserRemoteInfraFallbackFactory implements FallbackFactory<SysUserRemoteInfra> {

    @Override
    public SysUserRemoteInfra create(Throwable cause) {
        return new SysUserRemoteInfra() {
            
            private static final String SERVICE_UNAVAILABLE = "用户服务暂时不可用，请稍后重试";
            
            @Override
            public R getUserAuthInfo(String identifier) {
                return logAndFail("通过标识符获取用户认证信息", "identifier", identifier, cause);
            }
            
            @Override
            public R getUserAuthInfoByUsername(String username) {
                return logAndFail("通过用户名获取用户认证信息", "username", username, cause);
            }

            @Override
            public R getUserAuthInfoByAccount(String account) {
                return logAndFail("通过账户名获取用户认证信息", "account", account, cause);
            }

            @Override
            public R getUserAuthInfoByEmail(String email) {
                return logAndFail("通过邮箱获取用户认证信息", "email", email, cause);
            }

            @Override
            public R getUserAuthInfoByPhone(String phone) {
                return logAndFail("通过手机号获取用户认证信息", "phone", phone, cause);
            }

            @Override
            public R getUserPermissions(Long userId) {
                log.error("获取用户权限失败: userId={}", userId, cause);
                return R.ok(new ArrayList<>()); // 返回空列表，保持服务可用
            }

            @Override
            public R getUserRoles(Long userId) {
                log.error("获取用户角色失败: userId={}", userId, cause);
                return R.ok(new ArrayList<>()); // 返回空列表，保持服务可用
            }

            @Override
            public R isAccountActive(Long userId) {
                log.error("验证账户状态失败: userId={}", userId, cause);
                return R.ok(false); // 降级时默认账户不可用，安全第一
            }


            
            private R logAndFail(String operation, String paramName, Object paramValue, Throwable cause) {
                log.error("{}失败: {}={}", operation, paramName, paramValue, cause);
                return R.failed(null, SERVICE_UNAVAILABLE);
            }
        };
    }
}